library(reshape2)
library(RColorBrewer)
library(tidyverse)

######################################################
# Figure 4: The Policy Consequences of Postal Voting 
# in Close Referendums (Individual-level Data)
######################################################

data <- read.dta("simulation_input_interest_and_income.dta")

data <- data[is.na(data$votechoice_agg_pv_corr)==F,] # drop close elections with no information about low and high interest

data$anr_num_rev <- max(data$anr_num)-data$anr_num+1 

xlabel <- data$title_en
xbreaks <- as.numeric(data$anr_num_rev)

xlabel_alt <- paste(xlabel," (",data$year,")",sep="")

df <- melt(data, id=c("anr","anr_num","anr_num_rev","titel"))

df <- df[df$variable=="volkjaproz" | df$variable=="votechoice_agg_npv_corr"| df$variable=="votechoice_agg_pv_corr", ]

df <- df[is.na(df$value)==F , ] # cut votes with no information about low and high interest


cbind(factor(df$variable),df$value,df$anr_num)

col.set <- c("black",brewer.pal(3,"Set1")[1:2])

df$value <- as.numeric(df$value)
df$value<-as.numeric(df$value/100)


col.set <- c("black",brewer.pal(3,"Set1")[1:2])


ggplot(df, aes(y = value,x = anr_num_rev, shape=factor(variable), colour=factor(variable))) +
  geom_point(size=3.8) + 
  theme_bw(base_size = 30)  + 
  ylab("\n Yes share\n") + xlab("") +
  coord_flip() +
  scale_y_continuous(limits = c(0.45, 0.55),labels=percent) +
  scale_x_continuous(breaks=xbreaks,labels=xlabel_alt) +
  scale_shape_manual(values=c(15,16,17),name = "",labels = c("Observed  ","No Postal Voting  ","Postal Voting")) +
  scale_colour_manual(values=col.set,name = "",labels = c("Observed  ","No Postal Voting  ","Postal Voting")) +  
  theme(legend.direction = "horizontal", legend.position = "bottom") +
  geom_hline(yintercept = 0.5,linetype=2) +
  theme(panel.grid.minor.y =  element_line(colour = "white", size = 0.5,linetype="dotted")) +
  theme(legend.key = element_blank(), strip.background = element_rect(colour="black", fill="grey90" ) )



ggsave(file="Figure4.pdf",width=14,height=10 )
